import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { SetupStoreId } from '@/enum';
import { useRouterPush } from '@/hooks/common/router';
import { fetchGetUserInfo, fetchLogin } from '@/service/api';
import { fetchGetAllRoles, fetchGetRoleButtons } from '@/service/api/system-manage';
import { localStg } from '@/utils/storage';
import { $t } from '@/locales';
import { useRouteStore } from '../route';
import { useTabStore } from '../tab';
import { clearAuthStorage, getToken } from './shared';

export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
  const route = useRoute();
  const routeStore = useRouteStore();
  const tabStore = useTabStore();
  const { toLogin, redirectFromLogin } = useRouterPush(false);
  const { loading: loginLoading, startLoading, endLoading } = useLoading();

  const token = ref(getToken());

  const userInfo: Api.Auth.UserInfo = reactive({
    userId: '',
    userName: '',
    roles: [],
    buttons: []
  });

  /** is super role in static route */
  const isStaticSuper = computed(() => {
    const { VITE_AUTH_ROUTE_MODE, VITE_STATIC_SUPER_ROLE } = import.meta.env;

    return VITE_AUTH_ROUTE_MODE === 'static' && userInfo.roles.includes(VITE_STATIC_SUPER_ROLE);
  });

  /** Is login */
  const isLogin = computed(() => Boolean(token.value));

  /** Reset auth store */
  async function resetStore() {
    const authStore = useAuthStore();

    clearAuthStorage();

    authStore.$reset();

    if (!route.meta.constant) {
      await toLogin();
    }

    tabStore.cacheTabs();
    routeStore.resetStore();
  }

  /**
   * Login
   *
   * @param userName User name
   * @param password Password
   * @param [redirect=true] Whether to redirect after login. Default is `true`
   */
  async function login(userName: string, password: string, redirect = true) {
    startLoading();

    const { data, error } = await fetchLogin(userName, password);
    const loginToken = data;
    // console.log('login fetchLogin 返回:', { loginToken, error });

    if (!error) {
      const pass = await loginByToken(loginToken);
      console.log('loginByToken 执行结果:', pass);
      if (pass) {
        // 重置路由状态并重新初始化路由
        routeStore.isInitAuthRoute = false;
        await routeStore.initAuthRoute();

        await redirectFromLogin(redirect);
        console.log('已调用 redirectFromLogin，参数:', redirect);
        window.$notification?.success({
          message: $t('page.login.common.loginSuccess'),
          description: $t('page.login.common.welcomeBack', { userName: userInfo.userName })
        });
      }
    } else {
      resetStore();
    }

    endLoading();
  }

  async function loginByToken(loginToken: any) {
    if (!loginToken || typeof loginToken !== 'object') {
      console.error('loginByToken: loginToken is invalid', loginToken);
      window.$notification?.error({ message: '登录失败', description: '后端未返回有效的 token 信息' });
      return false;
    }
    // 1. stored in the localStorage, the later requests need it in headers
    localStg.set('token', loginToken.token || loginToken.accessToken);
    localStg.set('refreshToken', loginToken.refreshToken);
    // console.log('loginByToken 设置 token:', loginToken.token || loginToken.accessToken);
    // 2. get user info
    const pass = await getUserInfo();
    console.log('getUserInfo 执行结果:', pass);
    if (pass) {
      token.value = loginToken.token || loginToken.accessToken;
      return true;
    }
    return false;
  }

  async function getUserInfo() {
    const { data: info, error } = await fetchGetUserInfo();
    if (error) {
      window.$notification?.error({ message: '获取用户信息失败，请刷新重试', description: error.message });
      return false;
    }
    if (!error) {
      // update store
      Object.assign(userInfo, info);
      if (!info.roles || info.roles.length === 0) {
        window.$notification?.error({ message: '用户信息 roles 字段为空，无法跳转首页' });
      }

      // 获取用户按钮权限
      try {
        const userRoles = info.roles;
        if (userRoles && userRoles.length > 0) {
          // console.log('获取用户按钮权限，用户角色:', userRoles);

          // 获取所有角色信息，用于角色code到ID的映射
          const allRoles = await getAllRoles();
          if (allRoles && allRoles.length > 0) {
            const roleCodeToIdMap = new Map<string, number>();
            allRoles.forEach(role => {
              roleCodeToIdMap.set(role.roleCode, role.id);
            });
            // console.log('角色code到ID映射:', Object.fromEntries(roleCodeToIdMap));

            // 获取用户所有角色的按钮权限
            const allButtonCodes = new Set<string>();
            const roleButtonPromises = userRoles.map(async roleCode => {
              const roleId = roleCodeToIdMap.get(roleCode);
              if (!roleId) {
                console.warn(`未找到角色code ${roleCode} 对应的角色ID`);
                return;
              }

              // console.log(`获取角色 ${roleCode}(ID: ${roleId}) 的按钮权限...`);
              const roleButtonsResponse = await fetchGetRoleButtons(Number(roleId));
              if (roleButtonsResponse.data && Array.isArray(roleButtonsResponse.data)) {
                roleButtonsResponse.data.forEach(buttonCode => allButtonCodes.add(buttonCode));
                // console.log(`角色 ${roleCode} 的按钮权限:`, roleButtonsResponse.data);
              }
            });

            await Promise.all(roleButtonPromises);
            const userButtonCodes = Array.from(allButtonCodes);
            // console.log('合并后的用户按钮权限:', userButtonCodes);

            // 更新用户信息中的按钮权限
            userInfo.buttons = userButtonCodes;
          }
        }
      } catch (buttonError) {
        console.warn('获取用户按钮权限失败:', buttonError);
        userInfo.buttons = [];
      }

      return true;
    }

    return false;
  }

  /** 缓存所有角色信息，避免重复请求 */
  const allRolesCache = ref<Api.SystemManage.AllRole[]>([]);

  /** 获取所有角色信息 */
  async function getAllRoles(): Promise<Api.SystemManage.AllRole[]> {
    // 如果缓存中有数据，直接返回
    if (allRolesCache.value.length > 0) {
      return allRolesCache.value;
    }

    try {
      const allRolesResponse = await fetchGetAllRoles();
      if (allRolesResponse.data && Array.isArray(allRolesResponse.data)) {
        allRolesCache.value = allRolesResponse.data;
        return allRolesResponse.data;
      }
      return [];
    } catch (error) {
      console.error('获取所有角色信息失败:', error);
      return [];
    }
  }

  async function initUserInfo() {
    const hasToken = getToken();

    if (hasToken) {
      const pass = await getUserInfo();

      if (!pass) {
        resetStore();
      }
    }
  }

  return {
    token,
    userInfo,
    isStaticSuper,
    isLogin,
    loginLoading,
    resetStore,
    login,
    initUserInfo,
    getAllRoles
  };
});
